#include "common.h"

#include "FastLED.h"

#define DEFAULT_LED_BRIGHTNESS 100
#define BREATH_BRI_NUM 123

const uint8_t breath_brightness[BREATH_BRI_NUM] = { 36, 38, 41, 44, 46, 49, 51, 54, 59, 61, 64, 67, 72, 74, 79, 82, 87, 90, 95, 97, 102, 108, 113, 115, 120, 125, 131, 136, 141, 146, 148, 154, 159, 164, 169, 174, 179, 184, 189, 195, 200, 202, 207, 212, 215, 220, 225, 228, 230, 236, 238, 241, 243, 246, 248, 248, 251, 253, 253, 253, 253, 253, 253, 253, 253, 253, 251, 248, 248, 246, 243, 241, 238, 236, 230, 228, 225, 220, 215, 212, 207, 202, 200, 195, 189, 184, 179, 174, 169, 164, 159, 154, 148, 146, 141, 136, 131, 125, 120, 115, 113, 108, 102, 97, 95, 90, 87, 82, 79, 74, 72, 67, 64, 61, 59, 54, 51, 49, 46, 44, 41, 38, 36 };
static uint32_t port_color[USB_PORT_NUMS] = { 0 };

#define LED_TYPE WS2812  // LED灯带型号
#define COLOR_ORDER GRB  // RGB灯珠中红色、绿色、蓝色LED的排列顺序

static uint16_t rgbLeds = USB_PORT_NUMS;
static CRGB myColor = CRGB(0, 0, 0);

CRGB *leds;

static void rgb_reset() {
  FastLED.setBrightness(DEFAULT_LED_BRIGHTNESS);
}

static void rgb_init() {
  rgbLeds = RGB_LED_NUM;
  myColor = CRGB(0, 255, 0);
  leds = new CRGB[rgbLeds];
  LEDS.addLeds<LED_TYPE, RGB_LED_PIN, COLOR_ORDER>(leds, rgbLeds);
  rgb_reset();
  FastLED.clear(true);
}

void task_led(void *pvParameters) {
  rgb_init();

  for (;;) {
    for (int i = 0; i < USB_PORT_NUMS; i++) {
      if (inaData[i].portStatus == USB_PORT_ALERT) {
        // 警告，蓝色
        leds[i] = CHSV(160, 255, 255);
      } else if (inaData[i].portStatus == USB_PORT_OC) {
        // 过流，紫色
        leds[i] = CHSV(210, 255, 255);
      } else if (inaData[i].portStatus == USB_PORT_ON) {
        if (inaData[i].current == 0) {
          // 未插或者没电流，弱白色
          leds[i] = CRGB(30, 30, 30);
        } else {
          // 正常颜色显示
          uint16_t curr = constrain(inaData[i].current, 0, 1000);
          uint8_t hue = map(curr, 0, 1000, 128, 0);
          leds[i] = CHSV(hue, 255, 255);
        }
      } else if (inaData[i].portStatus == USB_PORT_OFF) {
        // 端口关闭，不亮
        leds[i] = 0;
      } else {
        // 端口未连接，不亮
        leds[i] = 0;
      }
    }
    for (int i = 0; i < BREATH_BRI_NUM; i++) {
      FastLED.setBrightness(breath_brightness[i] * DEFAULT_LED_BRIGHTNESS / 255);
      FastLED.show();
      vTaskDelay(30);
    }
    vTaskDelay(10);
  }
}
